package com.zhanggm.springboot.springbootdemo05.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器");
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse res = (HttpServletResponse)servletResponse;

        String requestURI = req.getRequestURI();
        //放行welcome页面
        if(requestURI.startsWith("/welcome") || requestURI.startsWith("/login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //模拟登陆，取用户的登陆信息
        Object userInfo = req.getSession().getAttribute("userInfo");
        if(userInfo==null){
            res.sendRedirect("/login");
        }
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
